﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
using System.Data.Objects;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wRouteList.xaml
    /// </summary>
    public partial class wRouteList : Window
    {
        private routelistEntities routelistEntities;

        private bool _selectMode = false;

        public bool SelectMode
        {
            get
            {
                return _selectMode;
                ;
            }
            set
            {
                _selectMode = value;

                ;
            }
        }

        public routelistEntities ContextDB
        {
            get { return (routelistEntities)GetValue(ContextDBProperty); }
            set { 
                SetValue(ContextDBProperty, value);
                routelistEntities = value;
            }
        }

        // Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContextDBProperty =
            DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wRouteList), new UIPropertyMetadata(null, new PropertyChangedCallback(propContextDB)));

        public static void propContextDB(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wRouteList item = d as wRouteList;
            if (null == item) return;
            routelistEntities it = e.NewValue as routelistEntities;
            if (null == it) return;
            item.routelistEntities = it;
        }



        public int RouteListID
        {
            get { return (int)GetValue(RouteListIDProperty); }
            set { SetValue(RouteListIDProperty, value); }
        }

        // Using a DependencyProperty as the backing store for RouteListID.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RouteListIDProperty =
            DependencyProperty.Register("RouteListID", typeof(int), typeof(wRouteList), new UIPropertyMetadata(0, new PropertyChangedCallback(propRouteListID)));

        public static void propRouteListID(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wRouteList item = d as wRouteList;
            if (null == item) return;
            int val = (int)e.NewValue;
            if (item.routelistEntities == null) return;
            RouteList rl = (from o in item.routelistEntities.RouteList where o.id == val select o).FirstOrDefault();
            item.RouteList = rl;
        }

        public RouteList RouteList
        {
            get { return (RouteList)GetValue(RouteListProperty); }
            set { SetValue(RouteListProperty, value); }
        }

        // Using a DependencyProperty as the backing store for RouteList.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RouteListProperty =
            DependencyProperty.Register("RouteList", typeof(RouteList), typeof(wRouteList), new UIPropertyMetadata(null));

        

        public wRouteList()
        {
            InitializeComponent();
        }

        private string getRLNumber(DateTime dateDoc)
        {
            string result = "";
            try
            {
                int ordval = dateDoc.Year;
                routelistEntities dbe = new routelistEntities();
                RouteListSeq item = new RouteListSeq();
                item.ordval = ordval;
                dbe.RouteListSeq.AddObject(item);
                dbe.SaveChanges();
                result = item.number;
                dbe.SaveChanges();
            }
            catch (Exception)
            {
            }
            return result;
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            DateTime dt;
            DateTime wrkDate = DateTime.Now;
            System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
            if (null == routeListViewSource) return;
            IEditableCollectionView vw = (IEditableCollectionView)routeListViewSource.View;
            if (null == vw) return;
            RouteList item = vw.AddNew() as RouteList;
            wrkDate = DateTime.Now.AddDays(1);
            item.datedoc = wrkDate.ToShortDateString();
            item.dt_datedoc = wrkDate;
            if (DateTime.TryParse(item.datedoc, out dt))
                item.nomdog = getRLNumber(dt);
            vw.CommitNew();
            //System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
            routeListViewSource.View.MoveCurrentTo(item);
            routeListDataGrid.ScrollIntoView(item);
            SaveData();
        }

        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
            if (null == routeListViewSource) return;
            RouteList item = routeListViewSource.View.CurrentItem as RouteList;
            if (null == item) return;
            var sch = (from o in item.RouteListSchedule select o).ToList();
            var info = (from o in item.RouteListInfo select o).ToList();
            foreach (var it1 in info)
            {
                routelistEntities.DeleteObject(it1);
            }
            foreach (var it1 in sch)
            {
                routelistEntities.DeleteObject(it1);
            }
            routelistEntities.DeleteObject(item);
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
            if (null == routeListViewSource) return;
            RouteList item = routeListViewSource.View.CurrentItem as RouteList;
            if (null == item) return;
            wRouteListItem wnd = new wRouteListItem();
            //wnd.ContextDB = routelistEntities;
            //wnd.RouteList = item;
            wnd.RouteListID = item.id;
            if (wnd.ShowDialog() == true)
            {
                routelistEntities.Refresh(RefreshMode.StoreWins, item);
            };
        }

        private System.Data.Objects.ObjectQuery<RouteList> GetRouteListQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.RouteList> routeListQuery = routelistEntities.RouteList;
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // routeListQuery = routeListQuery.Include("RouteList.driver").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            return routeListQuery;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            bool bEntity = true; 
            if (null == routelistEntities)
            {
                bEntity = false;
                routelistEntities = new RL.routelistEntities();
                buttonSelect.Visibility =  _selectMode == false ? System.Windows.Visibility.Hidden : System.Windows.Visibility.Visible;
            }
            
            
            // Загрузить данные в RouteList. Можно изменить этот код как требуется.
            System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
            System.Data.Objects.ObjectQuery<RL.RouteList> routeListQuery = this.GetRouteListQuery(routelistEntities);
            routeListViewSource.Source = from o in routelistEntities.RouteList orderby o.dt_datedoc select o;//routeListQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);//.OrderBy(o=>o.dt_datedoc).OrderBy(o=>o.nomdog);
           // routeListDataGrid.Items.SortDescriptions.Add(new SortDescription("dt_datedoc", ListSortDirection.Ascending));
            //routeListDataGrid.Items.SortDescriptions.Add(new SortDescription("nomdog", ListSortDirection.Ascending));
            if (bEntity)
            {
                if (null != RouteList)
                {
                    routeListViewSource.View.MoveCurrentTo(RouteList);
                    routeListDataGrid.ScrollIntoView(RouteList);
                    
                }
            }
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == routelistEntities) return false;
            bResult = routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                routelistEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
        }

        private void buttonSelect_Click(object sender, RoutedEventArgs e)
        {
            CollectionViewSource cvs = (CollectionViewSource)this.FindResource("routeListViewSource");
            RouteList = cvs.View.CurrentItem as RouteList;
            RouteListID = RouteList.id;
            try
            {
                DialogResult = true;
            }
            catch (Exception)
            {
            }
        }

        private void buttonPrint_Click(object sender, RoutedEventArgs e)
        {
            wPrint wnd = new wPrint();
            wnd.Show();
        }

        private void buttonFind_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (null == routelistEntities) return;
                System.Windows.Data.CollectionViewSource routeListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("routeListViewSource")));
                if (null == routeListViewSource) return;
                RouteList RL = (from o in routelistEntities.RouteList where o.id == FindRL.RouteListID select o).FirstOrDefault();
                if (null != RL)
                {
                    routeListViewSource.View.MoveCurrentTo(RL);
                    routeListDataGrid.ScrollIntoView(RL);

                }
            }
            catch (Exception)
            { 
            }
        }
    }
}
